//
//  FindMeishiViewController.m
//  B段项目
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 徐茂怀. All rights reserved.
//

#import "FindMeishiViewController.h"
#import "SectionHeaderViewCollectionReusableView.h"
#import "FindFoodCollectionViewCell.h"
#import "FitHeader.h"
#import "SearchViewController.h"
static float const spaceBetweenColumns = 15.0;
static float const widthOfWord = 25;
@interface FindMeishiViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>
@property(nonatomic,strong)UICollectionView *collection;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *dataSourceArray;
@property(nonatomic,strong)NSMutableArray *selectArray;
@property(nonatomic,strong)NSMutableArray *isSingleLineArray;
@property(nonatomic, strong)SectionHeaderViewCollectionReusableView *headView;
@property(nonatomic, strong)UISearchBar *searchBar;
@end
@implementation FindMeishiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}
-(void)loadView
{
    [super loadView];
    self.title = @"发现美食";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
    [self getData];
    _selectArray = [NSMutableArray array];
     _isSingleLineArray = [NSMutableArray array];
    for (NSInteger i = 0; i < _dataArray.count; i ++) {
        [_selectArray addObject:@"0"];
        [_isSingleLineArray addObject:@"1"];
    }
  
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-sousuo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumInteritemSpacing = 15 * FitWidth;
    flowLayout.minimumLineSpacing = 15 * FitHeight;
    flowLayout.sectionInset = UIEdgeInsetsMake(15 * FitHeight, 15 * FitWidth, 15 * FitHeight, 15 * FitWidth);
    flowLayout.itemSize = CGSizeMake(75 * FitWidth, 30 * FitHeight);
    
    _collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) collectionViewLayout:flowLayout];
    [_collection registerClass:[SectionHeaderViewCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    _collection.bounces = YES;
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.backgroundColor = [UIColor whiteColor];
    [_collection registerClass:[FindFoodCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    [self.view addSubview:_collection];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
    self.hidesBottomBarWhenPushed = YES;
    SearchViewController *vc = [[SearchViewController alloc]init];
    vc.name = searchBar.text;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
-(void)searchAction
{
        _searchBar = [[UISearchBar alloc]init];
        _searchBar.delegate = self;
        [self.searchBar setBarStyle:0];
        self.searchBar.backgroundColor = [UIColor clearColor];
        self.navigationItem.titleView = _searchBar;
    _searchBar.placeholder = @"亲,今天想吃啥?";
        [_searchBar becomeFirstResponder];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(quxiao)];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
}
-(void)quxiao
{
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-sousuo.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    [_searchBar removeFromSuperview];
    [_searchBar resignFirstResponder];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_searchBar resignFirstResponder];
    NSLog(@"fs");
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([_selectArray[section] isEqualToString:@"1"]) {
        return [_dataArray[section] count];
    }else {
        CGFloat width = 0.0;
        NSInteger i = 0;
        for (NSDictionary *dic in _dataArray[section]) {
            width += [[dic objectForKey:@"Food_Name"] length] * widthOfWord + spaceBetweenColumns;
            if (width <= self.view.frame.size.width - spaceBetweenColumns) {
                i++;
            }else {
                [_isSingleLineArray replaceObjectAtIndex:section withObject:@"0"];
                break;
            }
        }
        return i;
    }}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FindFoodCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    cell.array = [NSArray arrayWithArray:_dataArray[indexPath.section]];
    cell.label.text = [[_dataArray[indexPath.section]objectAtIndex:indexPath.row]objectForKey:@"Food_Name"];
    return cell;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return  _selectArray.count;
}
#pragma mark 头视图size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {self.view.frame.size.width, 40.0};
    return size;
}
#pragma mark 每个Item大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellSting = [[_dataArray[indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"Food_Name"];
    return CGSizeMake([self lengthWithString:cellSting] * widthOfWord, 30.0);
}
-(CGFloat)lengthWithString:(NSString *)string
{
    return [string length];
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        SectionHeaderViewCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
        headView.titleLabel.text = _sectionArray[indexPath.section];
        if ([_isSingleLineArray[indexPath.section] isEqualToString:@"0"]) {
            if ([_selectArray[indexPath.section] isEqualToString:@"0"]) {
                headView.button.myImageView.image = [UIImage imageNamed:@"iconfont-zhankaizhankai"];
                headView.button.unfoldOrBackLabel.text = @"展开";
            }else {
                headView.button.myImageView.image = [UIImage imageNamed:@"T62U6IL@HFI6(XPD4ZRGMMB.jpg"];
                headView.button.unfoldOrBackLabel.text = @"收起";
            }
            [headView.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            headView.button.tag = 1000 + indexPath.section;
        }
        
        return headView;
    }else {
        return nil;
    }

}
-(void)buttonAction:(UIButton *)button
{
    if ([_selectArray[button.tag - 1000] isEqualToString:@"0"])
    {
        [_selectArray replaceObjectAtIndex:button.tag - 1000 withObject:@"1"];
        [_collection reloadSections:[NSIndexSet indexSetWithIndex:button.tag - 1000]];
    }else {
        [_selectArray replaceObjectAtIndex:button.tag - 1000 withObject:@"0"];
        [_collection reloadSections:[NSIndexSet indexSetWithIndex:button.tag - 1000]];
    }
}

-(void)pushTOnextView
{
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
      self.hidesBottomBarWhenPushed = YES;
    [_searchBar resignFirstResponder];
    FindFoodCollectionViewCell *cell = (FindFoodCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
   [UIView animateWithDuration:.2 animations:^{
       cell.alpha = 0.5;
       cell.transform = CGAffineTransformMakeScale(1.4f, 1.4f);
   } completion:^(BOOL finished) {
       [UIView animateWithDuration:.2 animations:^{
           cell.alpha = 1.0;
           cell.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
       } completion:^(BOOL finished) {
           FindListViewController *vc = [[FindListViewController alloc]init];
           vc.name = [[_dataArray[indexPath.section]objectAtIndex:indexPath.row]objectForKey:@"Food_Name"];
           [self.navigationController pushViewController:vc animated:YES];
           self.hidesBottomBarWhenPushed = NO;
       }];
       
   }];
    
  
   
    
}

-(void)getData
{
    _sectionArray = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data.json" ofType:nil];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:filePath];
    NSError *error;
    NSArray *array = [NSArray array];
    array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    for (NSDictionary *dic in array) {
        [_sectionArray addObject:[dic objectForKey:@"Type"]];
        [_dataArray addObject:[dic objectForKey:@"Symptoms"]];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
